<template>
    <div class="loan-in-share" v-if='pageLoaded'>
        <!-- wrapper -->
        <div class="wrapper">
            <img src="../images/sharelanding_head.jpg" width="100%">
            <div class="loan-detail-main">
                <div class="loan-detail-user">
                    <span class="loan-detail-user__avatar"><img :src="loanUserInfo.user.avatar || placeholderImg" alt=""></span>
                    <div class="loan-detail-user__info">
                        <p class='name'>{{loanUserInfo.user.realName}}</p>
                        <p>借款人</p>
                    </div>
                    <span class="button short transparent" @click='goReportDetail'>信用报告</span>
                </div>
                <div class="loan-detail-number">
                    <p class="loan-detail-number__number">编号: {{number}}</p>
                    <div class="loan-detail-number__status">有效期: <count-down :date='detail.borrowEffectiveTime'></count-down></div>
                </div>
                <div class="loan-detail-money">
                    <div class="loan-detail-money__total">
                        <p class='text'>借款总额</p>
                        <span class='number'>{{detail.borrowAmount | toYuan}}元</span>
                    </div>
                    <ul class="loan-detail-money__list">
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.yearRate/100}}%</span>
                            <p>年化利率</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.serviceFee | toYuan}}</span>
                            <p>服务费(元)</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.interestAmount | toYuan}}</span>
                            <p>预计利息(元)</p>
                        </li>
                    </ul>
                </div>
                <div class="loan-detail-info">
                    <ul class="card__info">
                        <li class="card__info-item">发布日期：{{ detail.createdAt | dateFormat  }}</li>
                        <li class="card__info-item">借款时长：{{ detail.borrowDays  }}天</li>
                        <li class="card__info-item">还款方式：{{ detail.repayWayStr  }}</li>
                        <li class="card__info-item">借款用途：{{ detail.borrowUsage  }}</li>
                        <li class="card__info-item">服务费：{{detail.serviceFeeRate/100}}% | {{detail.serviceFee | toYuan}}元</li>
                    </ul>
                    <!-- <p class="card__info-item full">补充说明：{{detail.addSay || placeholder}}</p>  -->
                    <template v-if='detail.imageSay && detail.imageSay.length'>
                        <div class="card__info-item">图片说明：</div>
                        <ul class="loan-detail-info__pics">
                            <li class="loan-detail-info__pic" v-for='item in detail.imageSay' @click='imgViewShow(item.url)'>
                                <img :src="item.url">
                            </li>
                        </ul>
                    </template>
                    <div class="loan-detail-agreement"><span class="button short pure" @click='showAgreement = true'>查看借款协议</span></div>
                </div>
            </div>
            
        </div>
            
        <!-- footer -->
        <!--<transition name='fade'>-->
            <footer class="single-button" v-if='!detail.isMyPublishBorrow'>
                <span class="button purple" @click='confirm'>联系TA</span>
            </footer>
        <!--</transition>-->

        <agreement
            :show='showAgreement'
            @close='showAgreement=false'></agreement>

        <confirm 
            :show='show_modal_reject_apply'
            @close='show_modal_reject_apply = false'
            @confirm='rejectApply'
            title='确认拒绝申请'
            tips='是否确认拒绝申请'></confirm>
        <image-view 
            :url='currentImg' 
            :show='modal_img_show' 
            @close='modal_img_show = false'></image-view>

        <pay-detail
            :amount='detail.borrowAmount'
            :show='showPayDetail'
            @close='showPayDetail=false'
            @finish='payDetailFinish'></pay-detail>

        <pay-password
            :show='showPayPassword'
            @close='showPayPassword=false'
            @finish='payFinish'></pay-password>

        <sms-code
            v-if='userInfo.user'
            :show='showSmsCode'
            type='LEND'
            :mobile='userInfo.user.mobile'
            @close='showSmsCode=false'
            @finish='smsFinish'></sms-code>

        <modal
            :show='show_modal_qr'
            @close='show_modal_qr = false'>
            <div class="modal-qr">
                <img src="../images/qr.png" width="240">
            </div>
        </modal>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import confirm from '../components/Confirm.vue'
    import countDown from '../components/CountDown.vue'
    import payPassword from '../components/PayPassword.vue'
    import payDetail from '../components/PayDetail.vue'
    import smsCode from '../components/SmsCode.vue'
    import toYuan from '../filters/filter-toYuan'
    import imageView from '../components/ImageView.vue'
    import modal from '../components/Modal.vue'
    import agreement from '../components/Agreement.vue'
    import dateFormat from '../filters/filter-dateFormat'
    import  { mapGetters, mapActions }  from 'vuex'
    import { loanInApi, loanOutApi, userApi, payApi, contactApi } from '../api/api'
    import { getQueryString } from '../utils/utils'
    import moment from 'moment'

    export default {
        components:{
            confirm,
            modal,
            countDown,
            agreement,
            imageView,
            payPassword,
            payDetail,
            smsCode
        },
        filters:{
            toYuan,
            dateFormat,
        },
        data() {
            return {
                placeholderImg:require('../images/loading_1.png'),
                placeholder:'--',
                pageLoaded:false,
                number:this.$route.params.number,
                passwordPass:false,
                payWay:'',
                showAgreement:false,
                showPayPassword:false,
                showPayDetail:false,
                showSmsCode:false,
                show_modal_qr:false,
                modal_img_show:false,
                show_modal_reject_apply:false,
                smsCode:'',
                currentImg:'',
                detail:{},
                loanUserInfo:{},
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            userInfo(){
                return this.localInfo.userInfo
            },
            needLogin(){
                return this.localInfo.needLogin
            },
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'setUserInfo',
                'setGoHome',
                'setShare',
            ]),
            // function

            goRouter(name){
                this.$router.push({
                    name:name
                })
            },
            share(item){
                let protocol = location.protocol
                let host = location.host
                let pathname = location.pathname
                let search = location.search

                let realUrl = `${protocol}//${host}${pathname}${search}#share-loan-in/${item.borrowNo}`
                this.setShare({
                    message:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.borrowEffectiveTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () { 

                        },
                        cancel: function () { 

                        }
                    },
                    timeline:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                    qq:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.borrowEffectiveTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                })
            },
            withinOneDay(time){
                let now = moment()
                let diff = moment(time)
                let diffDays = diff.diff(now,'days')
                let diffTime = diff.diff(now)
                if(diffDays <= 0) return true
                return diffDays
                return true
            },
            goReportDetail(){
                if(!this.loanUserInfo.creditReport){
                    this.setMsgTip({
                        text:'该用户暂无信用报告！',
                        type:'warn'
                    })
                    return
                }
                this.$router.push({
                    name:'user-credit-report-detail',
                    params:{
                        no:this.loanUserInfo.creditReport.creditReportNo
                    }
                })
            },
            goBack(){
                history.go(-1)
            },
            rejectApply(){
                return loanOutApi.rejectApply({
                    borrowNo:this.number
                })
                .then(result=>{
                    this.hideLoading()
                    this.show_modal_reject_apply = false
                    history.go(-1)
                })
                .catch(error=> {
                    console.error(error);
                    this.show_modal_reject_apply = false
                    this.hideLoading()
                })
            },
            imgViewShow(url){
                this.currentImg = url
                this.modal_img_show = true
            },
            goSuccess(){
                this.$router.push({
                    name:'loan-in-success'
                })
            },
            confirm(){
                if(!this.userInfo.isFocus){
                    this.show_modal_qr = true
                    return
                }
                if(!this.needLogin){
                    this.setGoHome(true)
                    if(this.loanUserInfo.user){
                        this.$router.push({
                            name:'loan-in-detail-other',
                            params:{
                                number:this.number
                            }
                        })
                    }
                }
                else{
                    if(this.loanUserInfo.user){
                        this.setGoHome(true)
                        this.$router.push({
                            name:'bind-phone',
                            query:{
                                mobile:this.loanUserInfo.user.mobile,
                                number:this.number,
                                loan:'in'
                            }
                        })
                    }
                }
            },
            payDetailFinish(payObject){
                if(payObject.payType == 0){
                    this.payWay = 'CHARGE'
                }
                else{
                    this.payWay = 'BALANCE'
                }
                this.showPayDetail = false

                if(this.passwordPass) {
                    this.showSmsCode = true
                }
                else {
                    this.showPayPassword = true
                }
            },
            payFinish(password){
                this.password = password
                this.passwordPass = true
                this.showPayPassword = false
                this.showSmsCode = true
            },
            smsFinish(smsCode){
                this.smsCode = smsCode
                this.showSmsCode = false
                this.loanOut()
            },
            getDetail(){
                return loanInApi.detail({
                    borrowNo:this.number
                })
                .then(result=>{
                    this.hideLoading()
                    this.share(result)
                    this.detail = result
                })
            },
            getUserInfo(){
                return loanInApi.userInfo({
                    borrowNo:this.number
                })
                .then(result=>{
                    this.loanUserInfo = result
                })
            },
            loanOut(){
                this.showLoading()
                let params = {
                    payWay:this.payWay,
                    tradePassword:this.password,
                    smsCode:this.smsCode,
                    borrowNo:this.number,
                }
                loanOutApi.lendToIt(params)
                .then(result=> {
                    if(_.isEmpty(result)){
                        this.setMsgTip({
                            text:'出借成功',
                            type:'success'
                        })
                        this.$router.push({
                            name:'loan-IOU',
                            params:{
                                number:this.number
                            }
                        })
                        return 
                    }
                    this.payId = result.charge.payId
                    this.pay()
                })
                .catch(error=> {
                    console.error(error);
                    this.hideLoading()
                })
            },
            pay(){
                payApi.pay({
                    payId:this.payId,
                    returnUrl:location.href
                })
                .then(result=> {
                    location.href = result.payParam.url
                })
                .catch(error=> {
                    console.error(error);
                    this.hideLoading()
                })
            },
            storeUserInfo(){
                if(!this.userInfo){
                    userApi.getInfo()
                    .then(result=> {
                        this.setUserInfo(result)
                    })
                    .catch(error=> {
                        console.error(error);
                    })
                }
            }
        },
        created(){


            // if(!this.userInfo.isFocus){
            this.setGoHome(false)
            // }

            this.showLoading()
            this.storeUserInfo()
            Promise.all([this.getUserInfo(), this.getDetail()])
            .then(result=> {
                this.pageLoaded = true
                this.hideLoading()
            })
            .catch(error=> {
                console.error(error);
                this.pageLoaded = true
                this.hideLoading()
            })

        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-in-share{
        .wrapper{
            padding-bottom: 100px;
        }
        .loan-detail-main{
            background-color: #fff;
            padding:0 24px;
            position: relative;
        }
    }

</style>
